﻿using BarcodeDelay.bean;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BarcodeDelay.Transaction
{
    public class TransactionDatabase : ITransaction
    {
        private const int COLUMN_UPLOADINFO = 1;
        private const int COLUMN_RETRYCOUNT = 2;
        private DbOperatorFactory cameraDbFactory;
        private DbOperatorFactory localDbFactory;
        public event EventHandler<EarsDatabaseUpdate> OnDatabaseUpdate;

        private static TransactionDatabase instance;
        public static TransactionDatabase Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new TransactionDatabase();
                }
                return instance;
            }
        }

        private TransactionDatabase()
        {
        }

        public void Init(DbOperatorFactory _cameraDbFactory)
        {
            if(_cameraDbFactory==null)
            {
                StreamWriter swb2 = new StreamWriter(System.Environment.CurrentDirectory + "\\task.txt", true);
                swb2.WriteLine(System.DateTime.Now + "_cameraDbFactory==null：");
                swb2.Close();
            }
            
            this.cameraDbFactory = _cameraDbFactory;
        }

        public void InitLocal(DbOperatorFactory _localDbFactory)
        {
            this.localDbFactory = _localDbFactory;
        }

        public void ReadConfiguration()
        {

        }

        public void ShutDown()
        {

        }


        public bool insertBatchRecords(string strsql)
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    dbOperator.ExecuteUpdate(strsql);
                    return true;
                }
                catch (Exception ex)
                {
                    //Logger.LogError("TransactionDatabase.insertBatchRecords 异常", ex.Message);
                }
                return false;
            }

        }

        public void updatePackFlag(string strUuidList, int flag)
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string strsql = "update tt_sto_package_result  set status=" + flag.ToString() + ",tryCount=0 where id in(" + strUuidList + ")";
                    dbOperator.ExecuteUpdate(strsql);
     

                }
                catch (Exception ex)
                {
                    //Logger.LogError("TransactionDatabase.updatePackFlag 异常", ex.Message);
                }
            }
        }


        public void updateTryCount(string strUuidList)
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string strsql = "update tt_sto_package_result set tryCount=tryCount+1 where id in(" + strUuidList + ")";
                    dbOperator.ExecuteUpdate(strsql);
                }
                catch (Exception ex)
                {
                    //Logger.LogError("TransactionDatabase.updateTryCount 异常", ex.Message);
                }
            }
        }








        public void getSiteOpUserMap(out Hashtable ht)
        {
            ht = new Hashtable();
            ht.Clear();
            try
            {
                Hashtable htTmp = new Hashtable();
                using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
                {
                    string sql = "SELECT * FROM tt_sto_arrival_site where status=1";
                    dbOperator.ExecuteQuery(sql);
                    DbDataReader dr = dbOperator.Reader;
                    if (dr.HasRows)//如果有数据
                    {

                        while (dr.Read())
                        {
                            htTmp[dr[1].ToString()] = dr[3].ToString();
                        }
                        dr.Close();
                    }
                }

                using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
                {
                    string sql = "SELECT DISTINCT nextStaCode from tt_sto_package_result where `status`=2 and stoMode='arrival' and nextStaCode!='none'";
                    dbOperator.ExecuteQuery(sql);
                    DbDataReader dr = dbOperator.Reader;
                    if (dr.HasRows)//如果有数据
                    {

                        while (dr.Read())
                        {
                            if (htTmp.ContainsKey(dr[0].ToString()))
                            {
                                string strOpUser = htTmp[dr[0].ToString()] as string;
                                ht[dr[0].ToString()] = strOpUser;
                            }

                        }
                        dr.Close();
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }


       

        public void addMsgContent(string msgContent,string taskMsg)
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string sql = "insert into tt_reply_wechat (replymsg,taskmsg,recordDate) values ('" + msgContent+"','"+ taskMsg+"','"+ System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"')";
                    int res=dbOperator.ExecuteUpdate(sql);

                }
                catch (Exception ex)
                {

                }
            }
        }

        public void updateMsgFlag(string id)
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string sql = "update tt_con_recv set handleFlag=1 where id="+ id;
                    dbOperator.ExecuteQuery(sql);

                }
                catch (Exception ex)
                {

                }
            }
        }

        public void deleteHistoryData()
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string sql = "delete from tt_con_recv  where recordDate<" + System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " " + "00:00:00"; ;
                    dbOperator.ExecuteQuery(sql);

                    sql = "delete from tt_reply_wechat  where recordDate<" + System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " " + "00:00:00"; ;
                    dbOperator.ExecuteQuery(sql);


                }
                catch (Exception ex)
                {

                }
            }
        }


        public ArrayList getAllUploadedPackageEx(out Hashtable ht_packageCode)
        {
            ht_packageCode = new Hashtable();
            ArrayList arListRes = new ArrayList();
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string sql = "SELECT packageCode,slot,recordDate from tb_package_slot where status=2 " +
                        " and recordDate> '2017-04-23 00:00:00' and recordDate< '2017-04-23 20:30:00'";
                    dbOperator.ExecuteQuery(sql);
                    DbDataReader dr = dbOperator.Reader;
                    while (dr.Read())
                    {
                        if (!arListRes.Contains(dr[0].ToString()))
                        {
                            arListRes.Add(dr[0].ToString());
                            string key = dr[0].ToString();
                            string val = dr[1].ToString() + "," + dr[2].ToString();
                            ht_packageCode[key] = val;
                        }

                    }
                    dr.Close();

                }
                catch (Exception ex)
                {

                }
            }
            return arListRes;

        }

     


        public void excuetesql(string strSql)
        {
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {

                    dbOperator.ExecuteUpdate(strSql);

                }
                catch (Exception ex)
                {
                    //Logger.LogError("excuetesql 批量同步插入 异常", ex.Message);
                }
            }
        }


        public int excuteUpdateFeed(string strSql)
        {
            int rowCount = 0;
            using (DbOperator dbOperator = this.localDbFactory.CreateDbOperator())
            {
                try
                {

                    rowCount = dbOperator.ExecuteUpdate(strSql);

                }
                catch (Exception ex)
                {
                    //Logger.LogError("excuteUpdateFeed 批量同步插入 异常", strSql);
                }
            }
            return rowCount;
        }

        public int excuteUpdate(string strSql)
        {
            int rowCount = 0;
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {

                    rowCount = dbOperator.ExecuteUpdate(strSql);

                }
                catch (Exception ex)
                {

                }
            }
            return rowCount;
        }

        private void DoTriggerUpdateDatabaseEvent(object dummyObj)
        {
            if (this.OnDatabaseUpdate != null)
            {
                
            }
        }
        public ArrayList getUnhandleMsg()
        {
            ArrayList arlistRes = new ArrayList();
            
            string strSortModel = "dep";
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string strsql = "select * from tt_con_recv where  handleFlag=0 order by id asc limit 10";
                    dbOperator.ExecuteQuery(strsql, null);
                    DbDataReader reader = dbOperator.Reader;
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            HandleBean handleBean = new HandleBean();
                            handleBean.msg = reader["contentMsg"].ToString();
                            handleBean.handleID = Convert.ToInt32(reader["id"].ToString());
                            arlistRes.Add(handleBean);
                        }
                        reader.Close();
                    }
                       

                    //DoTriggerUpdateDatabaseEvent(null);
                }
                catch (Exception ex)
                {
                    string dir = System.Environment.CurrentDirectory;
                    StreamWriter swb = new StreamWriter(dir + "\\task.txt", true);
                    swb.WriteLine(System.DateTime.Now + "getUnhandleMsg error：" + ex.ToString());
                    swb.Close();
                    //Logger.LogError("getSortModel 异常", ex.Message);
                }
            }
            return arlistRes;
        }

        public ArrayList getRecentMsg(out bool res)
        {
            res = true;
            ArrayList arlistRes = new ArrayList();
            int step = 1;
            using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
            {
                try
                {
                    string strsql = "select * from tt_reply_wechat  order by id desc limit 20";
                    dbOperator.ExecuteQuery(strsql, null);
                    step++;
                    DbDataReader reader = dbOperator.Reader;
                    if (reader.HasRows)
                    {
                        step++;
                        while (reader.Read())
                        {
                            step++;
                            string taskmsg = reader["taskmsg"].ToString();
                            string[] arr = taskmsg.TrimEnd('$').Split('$');
                            foreach(string line in arr)
                            {
                                arlistRes.Add(line);
                            }
                        }
                        reader.Close();
                    }


                    //DoTriggerUpdateDatabaseEvent(null);
                }
                catch (Exception ex)
                {
                    res = false;
                    string dir = System.Environment.CurrentDirectory;
                    StreamWriter swb = new StreamWriter(dir + "\\task.txt", true);
                    swb.WriteLine(System.DateTime.Now + "getRecentMsg error：step="+ step.ToString() +" ex"+ ex.ToString());
                    swb.Close();
                    //Logger.LogError("getSortModel 异常", ex.Message);
                }
            }
            return arlistRes;
        }

        public string[] getOpUserList(string strBeginTm)
        {
            string[] opUserList = null;
            try
            {
                string strUserList = "";
                using (DbOperator dbOperator = this.cameraDbFactory.CreateDbOperator())
                {
                    string sql = "SELECT DISTINCT workNumber from tt_sto_package_result where recordDate>'" + strBeginTm + "'";
                    dbOperator.ExecuteQuery(sql);
                    DbDataReader dr = dbOperator.Reader;
                    if (dr.HasRows)//如果有数据
                    {

                        while (dr.Read())
                        {
                            strUserList = strUserList + dr[0].ToString() + ",";

                        }
                        dr.Close();
                        strUserList = strUserList.Trim(',');
                        opUserList = strUserList.Split(',');

                    }
                }

            }
            catch (Exception ex)
            {
                //Logger.LogError("getOpUserList error", "获取工号列表异常" + ex.ToString());
            }
            return opUserList;
        }





        ////////////////////////////////End Of Class//////////////////////////////////////////
    }
}

